#!/usr/bin/env python
import csv, os
import hmmer3
import random
from dbbuild import *
#This script process that complete_valiset.csv file
#convert it into format:
#Acc | Start | End | Peptide | 0 |


def get_pdz(proteinID, pdz_num):
    #if protein got only one pdz domain return false
    #more than one, return domian num, from, to
    try:
        protein = ID2tree(proteinID)
    except:
        return False

    if protein is not False:
        protein_sequence = GetSequence(protein)
        pdz_domains = pdz2_ext(proteinID)
        if pdz_domains is not False:                
            for k in pdz_domains:
                if (k == ('PDZ ' + str(pdz_num))) or (int(pdz_num) == 1 and len(pdz_domains) == 1):
                    (start, end) = pdz_domains[k]
                    domain_sequence = protein_sequence[start-1:end-1]
                    #print "Sequence:", domain_sequence
                    return domain_sequence

        else:
            #no PDZ in this Uniprot XML File
            print "Does Not have PDZ domain indicated in Uniprot File", proteinID
            #raise ("Please check uniprot file", proteinID)
            return False
    else:
        raise


def nonbind(infile = 'complete_validset.csv'):
    validation_table = csv.reader(open(infile))
    #hmmscan_thres = 0.01
    #hmmdb = 'strucaln.hmm'
    #options_length = 5
    output = dict()
    row_count = 0 
    for row in validation_table:
        row_count += 1
        uniprotacc = row[5]
        peptide = row[4]
        pdz_num = row[3]

        if row[2] == 'non-binding':
            
            #use hmm profile to locate pdz? too stupid, just use uniprot file to locate
            sequence = get_pdz(uniprotacc, pdz_num)
            
            
            if sequence is not False:
                if output.has_key((uniprotacc, sequence)):

                    output[(uniprotacc, sequence)].add(peptide)
                else:
                    output[(uniprotacc, sequence)] = set()
                    output[(uniprotacc, sequence)].add(peptide)

            else:
                print uniprotacc, "Error."
                
        else:

            pass

    return output

if __name__ == '__main__':
    test = nonbind()
    
    for i in test:
        print i, test[i]
        